package com.brunogb.pages.server.interceptors;

import javax.servlet.http.HttpServletRequest;

import org.vraptor.Interceptor;
import org.vraptor.LogicException;
import org.vraptor.LogicFlow;
import org.vraptor.annotations.In;
import org.vraptor.annotations.Out;
import org.vraptor.view.ViewException;

import com.brunogb.pages.security.Protected;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author bruno bilescky
 *
 */
public class UserInterceptor implements Interceptor {
	
	@In private HttpServletRequest request; 

	@Out private UserService userService = UserServiceFactory.getUserService();
	
	@Out private boolean userLoggedin;
	
	@Out private User profile;
	
	@Out private String logoutUrl;
	
	@Out private String loginUrl;
	
	/* (non-Javadoc)
	 * @see org.vraptor.Interceptor#intercept(org.vraptor.LogicFlow)
	 */
	public void intercept(LogicFlow flow) throws LogicException, ViewException {
		try {
			userLoggedin = userService.isUserLoggedIn();
			profile = userService.getCurrentUser();
			if (userLoggedin){
				logoutUrl = userService.createLogoutURL("/");
			}else{
				loginUrl = userService.createLoginURL(request.getRequestURL().toString());
			}
			if (!flow.getLogicRequest().getLogicDefinition().getLogicMethod().getMetadata().isAnnotationPresent(Protected.class)){
				flow.execute();
			}else {
				if (userService.isUserLoggedIn()) {
					flow.getLogicRequest().getRequest().setAttribute("user", userService.getCurrentUser());
					flow.execute();
				} else {
					flow.getLogicRequest().getResponse().sendRedirect("/home");
				}
			}
		} catch (Exception e) {
			throw new LogicException(e);
		}
	}

	/**
	 * @return the userService
	 */
	public UserService getUserService() {
		return userService;
	}		
}
